/* Orbas:
 *     A open source CORBA Specification implementation from Huihoo.
 *
 * Copyright 2002-2003 Huihoo.org, Inc. All Right Reserved.
 *
 * This software is licensed under LGPL license.
 * See terms of license at gnu.org.
 *
 * For more information, visit:
 *
 * http://www.huihoo.org/orbas
 */

package org.huihoo.orbas.idl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

class Module extends Declaration implements Scope {

	public Definitions spec;

	private ScopeData scopeData;
	private String unreplacedName = null;

	public Module(int num) {
		super(num);
		pack_name = "";
	}

	public void setScopeData(ScopeData data) {
		scopeData = data;
	}

	public ScopeData getScopeData() {
		return scopeData;
	}

	public void setPackage(String s) {
		if (unreplacedName == null)
			unreplacedName = s;
		s = parser.pack_replace(s);

		if (pack_name.length() > 0) {
			// unreplacedName = unreplacedName + "." + pack_name;
			pack_name = s + "." + pack_name;
			spec.setPackage(s);
		} else {
			pack_name = s;

			if (lexer.needsJavaEscape(this))
				pack_name = "_" + s;

			name = pack_name;
			spec.setPackage(pack_name);
		}
	}

	String full_name() {
		return pack_name;
	}

	public void set_included(boolean i) {
		included = i;
		spec.set_included(i);
	}

	public void setEnclosingSymbol(IdlSymbol s) {
		if (enclosing_symbol != null && enclosing_symbol != s)
			throw new RuntimeException(
					"Compiler Error: trying to reassign container for " + name);
		enclosing_symbol = s;
		spec.setEnclosingSymbol(this);
	}

	public void parse() {
		try {
			NameTable.define(full_name(), "module");
		} catch (NameAlreadyDefined nad) {
			Environment.output(4, nad);
			parser.error("Module name " + full_name() + " already defined",
					token);
		}
		spec.parse();
	}

	public void print(PrintWriter ps) {
		if (parser.generateIR) {
			try {
				// Java Interface file

				String path = parser.out_dir + fileSeparator
						+ pack_name.replace('.', fileSeparator);
				File dir = new File(path);
				if (!dir.exists()) {
					if (!dir.mkdirs()) {
						org.huihoo.orbas.idl.parser.fatal_error(
								"Unable to create " + path, null);
					}
				}

				PrintWriter moduleWriter = new PrintWriter(
						new java.io.FileWriter(new File(dir, "_" + name
								+ "Module.java")));
				moduleWriter.println("package " + pack_name + ";\n");
				moduleWriter
						.println("/** \n * IR module information, generated by the orbas IDL compiler \n */");
				moduleWriter.println("public class _" + name + "Module {}");
				moduleWriter.close();

			} catch (IOException io) {
				Environment.output(2, io);
			}
		}
		spec.print(ps);
	}

	/**
	 * @return the original, unreplaced module name (needed to build a
	 *         repositoryID that is untouched by the compiler option -i2jpackage
	 */

	public String originalModuleName() {
		return unreplacedName;
	}

}
